package so.dun.mp3;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("DefaultLocale")
public class Mp3Activity extends Activity implements OnItemClickListener,OnClickListener, OnSeekBarChangeListener {

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private String[] ext={".mp3", ".wma",".txt"};//定义我们要查找的文件格式


    // 列表视图（显示歌曲列表）
    private ListView listView;
    private TextView textViewSongName;
    private TextView textViewTimeLength;
    private TextView textViewTimePosition;

    //消息处理器（消息是android线程间通信的机制）
    private Handler handler = new Handler();

    private SeekBar seekBar;

    // 歌曲名称
    private String[] songList;

    // 适配器：数据与视图之间的桥梁
    private ArrayAdapter<String> adapter;

    private ImageButton buttonPause;
    private ImageButton buttonStop;

    private File sdPath = null;

    /**
     * 创建活动的时候执行，加载布局文件，显示视图上的数据
     */
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 加载布局文件
        setContentView(R.layout.main);
        textViewSongName = (TextView) this.findViewById(R.id.textView_song_name);

        // 获得列表视图的引用
        listView = (ListView) this.findViewById(R.id.listView);
        buttonPause = (ImageButton) findViewById(R.id.imageButton_pause);
        buttonStop = (ImageButton) findViewById(R.id.imageButton_stop);
        textViewTimeLength = (TextView) findViewById(R.id.textView_time_length);
        textViewTimePosition=(TextView) findViewById(R.id.textView_time_position);

        seekBar = (SeekBar) findViewById(R.id.SeekBar);

        seekBar.setOnSeekBarChangeListener(this);

        buttonPause.setOnClickListener(this);
        buttonStop.setOnClickListener(this);

        // 加载音乐列表
//        loadSongList();
        new Search().execute();



        // 注册监听器
        listView.setOnItemClickListener(this);
    }
    /**
     * 程序正常启动：onCreate()->onStart()->onResume();
     正常退出：onPause()->onStop()->onDestory()
     */
    protected void onStart(){
        super.onStart();
//        if(!mediaPlayer.isPlaying()){
//            prepareMediaPlayer(0);
//        }
    }

    protected void onResume(){
        super.onResume();
        handler.post(updateSeekBar);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    protected void onPause(){
        super.onPause();
    }

    protected void onStop(){
        super.onStop();
    }

    protected void onDestroy(){
        super.onStop();
        super.onDestroy();
        mediaPlayer.reset();
    }

    File file=Environment.getExternalStorageDirectory();//获得SD卡的路径
    List<String> list = new ArrayList<String>();


    public void search(File file ,String[] ext){
        if(file!=null) {
            if (file.isDirectory()) {//如果是文件夹
                File[] listFile = file.listFiles();//列出所有的文件放在listFile这个File类型数组中
                if (listFile != null) {
                    for (int i = 0; i < listFile.length; i++) {
                        search(listFile[i], ext);//递归，直到把所有文件遍历完
                    }
                }
            } else {//否则就是文件
                String fileName = file.getAbsolutePath();//返回抽象路径名的绝对路径名字符串
                String name = file.getName();//获得文件的名称
                for (int i = 0; i < ext.length; i++){
                    if (fileName.endsWith(ext[i])) {//判断文件后缀名是否包含我们定义的格式
                        list.add(name);
                        break;
                    }
                }
            }
        }
    }



// （1）自定义方法，加载音乐列表
    private void loadSongList() {
        // TODO Auto-generated method stub
        // 判断SDCard是否可用
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // SD卡可用

            //sdPath = Environment.getExternalStorageDirectory();
            //boolean b = sdPath.canRead();
            //sdPath = new File("~/upload");
            search(file ,ext);
            // 获得SD卡中所有文件的名字
            /*songList = sdPath.list(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String filename) {
                    // TODO Auto-generated method stub
                    if (filename.endsWith(".txt") || filename.endsWith(".wma")) {
                        return true;
                    }
                    return false;
                }
            });*/

            songList = list.toArray(new String[list.size()]);
            if(songList != null){
                Arrays.sort(songList);
            }else{
                songList = new String[]{};
            }

        }
    }

    class Search extends AsyncTask<Void,Void,List<String>>{


        @Override
        protected List<String> doInBackground(Void... params) {
            loadSongList();
            return list;
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            // 创建适配器
            adapter = new ArrayAdapter<String>(Mp3Activity.this,android.R.layout.simple_list_item_1, songList);

            listView.setAdapter(adapter);
            Toast.makeText(Mp3Activity.this, "获取完成", Toast.LENGTH_LONG).show();
        }
    }


    /**
     * 实现了列表项单击监听器 (non-Javadoc)
     *
     * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView,
     *      android.view.View, int, long)
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
        // TODO Auto-generated method stub
        prepareMediaPlayer(index);
        mediaPlayer.start();
        handler.post(updateSeekBar);
        buttonPause.setImageResource(R.drawable.pause);
    }

    private void prepareMediaPlayer(int index) {
        //修改音乐的标题名
        String songName = songList[index];
        textViewSongName.setText(songName);

        //修改音乐的播放时间

        mediaPlayer.reset();
        //设置数据源
        try {
			/*mediaPlayer.setDataSource("/mnt/sdcard/"+songName);*/
            mediaPlayer.setDataSource(sdPath+"/"+songName);
            //准备
            mediaPlayer.prepare();

            int length = mediaPlayer.getDuration();

            textViewTimeLength.setText(formatTime(length));

            seekBar.setMax(length);


        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 格式化显示时间
     * @param time
     * @return
     */

    private String formatTime(int time) {
        time/=1000;
        int hour=time/60/60;
        int minute = time/60%60;
        int second = time%60;
        return String.format("%02d:%02d:%02d",hour,minute,second);
    }

    /**
     *
     * 实现了按钮单击的监听器
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.imageButton_pause:
                //System.out.println("pause");
                doPause();
                break;
            case R.id.imageButton_stop:
                //System.out.println("stop");
                doStop();
                break;
        }
        // TODO Auto-generated method stub

    }

    private void doPause() {
        // TODO Auto-generated method stub
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            buttonPause.setImageResource(R.drawable.play);
        }
        else {
            mediaPlayer.start();
            buttonPause.setImageResource(R.drawable.pause);
        }

    }

    private void doStop() {
        // TODO Auto-generated method stub
        if(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
        }
        buttonPause.setImageResource(R.drawable.play);
        prepareMediaPlayer(0);
    }



    //更新进度 回调任务
    private Runnable updateSeekBar = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            //更新UI
            int position = mediaPlayer.getCurrentPosition();
            textViewTimePosition.setText(formatTime(position));
            seekBar.setProgress(position);
            if(seekBar.getProgress()<seekBar.getMax()){
                handler.postDelayed(this, 100);
            }
        }
    };

    /*
     * 改变进度(non-Javadoc)
     * @see android.widget.SeekBar.OnSeekBarChangeListener#onProgressChanged(android.widget.SeekBar, int, boolean)
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
        // TODO Auto-generated method stub
        if(fromUser){
            mediaPlayer.seekTo(progress);
            textViewTimePosition.setText(formatTime(progress));
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
        //从队列中移除updateSeekBar线程
        handler.removeCallbacks(updateSeekBar);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
        mediaPlayer.start();
        handler.post(updateSeekBar);
        buttonPause.setImageResource(R.drawable.pause);
    }
}

